package com.automation.entity;

import com.automation.service.AppiumUtils;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

public class HomePage extends BasePage {
    public HomePage(AndroidDriver driver) {
        super(driver);
    }

    public void refreshAndWait() {
        AppiumUtils.pullToRefresh(driver);
        try {
            AppiumUtils.waitForElement(driver, By.xpath("//android.widget.TextView[@text=\"推荐\"]"), 30);
        }catch (Exception e){
            driver.pressKey(new KeyEvent(AndroidKey.BACK));
        }
    }

    public void openSearch() {
        click(By.xpath("//android.widget.RelativeLayout[@content-desc=\"搜索\"]"));
        try {
            Thread.sleep(500);    // 短暂等待
        } catch (InterruptedException e) {

        }
//        click(By.xpath("//*[@content-desc='搜索']"));
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        WebElement searchEditText = wait.until(ExpectedConditions.elementToBeClickable(
                By.xpath("//android.widget.EditText[@content-desc='search_keyword_edit']")));
        System.out.println("元素是否显示: " + searchEditText.isDisplayed());
        System.out.println("元素是否可用: " + searchEditText.isEnabled());
        searchEditText.sendKeys("美食");
        click(By.xpath("//android.widget.TextView[@content-desc=\"search_button\"]"));
    }


    public boolean isSearchOpened() {
         AppiumUtils.isElementPresent(driver, By.xpath("//android.widget.TextView[@text=\"商户\"]"), 15);
        click(By.xpath("//android.widget.TextView[@text=\"商户\"]"));
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        return true;
    }

}